package pro.cherish.knowledgedemothread;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-10 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：TestCountDownLatch
 * @Description 功能说明：
 * java.util.concurrent.CountDownLatch是一个并发构造，允许一个或者多个线程等待一系列指定操作的完成
 *
 * CountDownLatch以一个给定的数量初始化，countDown()每被调用一次，这一数量就减一，通过调用await()方法，线程可以阻塞等待这一数量到达零
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-10 cherish
 */

import java.util.concurrent.CountDownLatch;

public class TestCountDownLatch {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);
        Waiter waiter = new Waiter(latch);
        Waiter2 waiter2 = new Waiter2(latch);
        Decrementer decrementer = new Decrementer(latch);

        new Thread(waiter).start();
        new Thread(waiter2).start();
        new Thread(decrementer).start();
    }
}
class Waiter implements Runnable{
    CountDownLatch latch = null;
    public Waiter(CountDownLatch latch) {
        this.latch = latch;
    }
    @Override
    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Waiter Released");
    }
}
class Waiter2 implements Runnable{
    CountDownLatch latch = null;
    public Waiter2(CountDownLatch latch) {
        this.latch = latch;
    }
    @Override
    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Waiter2 Released");
    }
}
class Decrementer implements Runnable{
    CountDownLatch latch = null;
    public Decrementer(CountDownLatch latch) {
        this.latch = latch;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            this.latch.countDown();
            Thread.sleep(1000);
            this.latch.countDown();
            Thread.sleep(5000);
            this.latch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("CountDown减为0");
    }
}